package com.yunkaweilai.android.activity.operation.integral;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.CaptureActivity;
import com.yunkaweilai.android.activity.shop.ShopTypeActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.model.CodeMsgBean;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.ImageUploadModel;
import com.yunkaweilai.android.model.SimpleModel;
import com.yunkaweilai.android.model.integral.IntegralTypeListModel;
import com.yunkaweilai.android.model.shop.ShopInfoDiyModel;
import com.yunkaweilai.android.net.Glide.GlideUtils;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.PicturePickerHelper;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.MyToast;
import com.yunkaweilai.android.view.dialog.shop.ShopCodeSingleDialog;
import com.yunkaweilai.android.view.dialog.shop.ShopInfoImageDelDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.picker.DatePicker;
import okhttp3.Call;

import static com.yunkaweilai.android.utils.ImageUtilsK.deleteSingleFile;

/**
 * 新增礼品
 * Created by Administrator on 2017/6/14.
 */

public class AddIntegralActivity extends BaseActivity {


    public int SHOP_TYPE_CODE = 101;//分类
    public int SHOP_QR_CODE = 102;//二维码
    public int SHOP_COMPANY_CODE = 103;//单位
    public int IMG_SELECTION = 104;//图片上传

    @BindView(R.id.id_tv_shop_type)
    TextView idTvShopType; //商品类别
    @BindView(R.id.id_edt_code_num)
    EditText idEdtCodeNum;//商品编码
    @BindView(R.id.id_edt_good_name)
    EditText idEdtGoodName;//商品名称
    @BindView(R.id.id_tv_sell_price)
    EditText idTvSellPrice;//输入积分
    @BindView(R.id.id_tv_remarks)
    EditText idTvRemarks;//商品备注
    @BindView(R.id.id_edt_stock)
    EditText idEdtStock;//商品数量
    @BindView(R.id.id_img_add1)
    ImageView idImgAdd1;//添加图片
    @BindView(R.id.id_img_del)
    ImageView idImgDel;//删除图片
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    @BindView(R.id.id_switch_qiyong)
    Switch mSwitch;//启用商品
    @BindView(R.id.id_switch_zzdh)
    Switch mSwitch2;//自主充值
    @BindView(R.id.id_tv_add_tel)
    TextView mTextViewtel;//自动生成
    @BindView(R.id.id_edt_order)
    EditText idEdtOrder;//排序
    @BindView(R.id.id_edt_start_time)
    TextView idEdtStartTime;
    @BindView(R.id.id_edt_end_time)
    TextView idEdtEndTime;

    private Gson gson = new Gson();
    private String goods_category_id = "";//分类id
    private String mPicPath = "";//文件路径
    private String upload_img_url = "";
    private boolean isSingleCode = false;
    private ShopCodeSingleDialog dialog;
    private ArrayList<ShopInfoDiyModel.DataBean.InfoBean> diyList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_integral);
        ButterKnife.bind(this);
        new TitleBuilder(this).setLeftImage(R.mipmap.ic_go_back)
                .setTitleText("新增礼品")
                .setRightText("保存");
        idMultipleStatusView.showContent();
        mSwitch.setChecked(true);//默认启用商品
        mSwitch2.setChecked(false);//默认不启用商品自主兑换
        initDate();
        initClick();
        getCategory();

    }


    private void getCategory() {
        HttpRequest.postUrl(Api.APP_INTEGRAL_TYPE)
                .log(TAG).execute(new PostProcess.StringCallBack() {
            @Override
            public void onResponse(String json) {
                boolean checkCode = Utils.checkCode(AddIntegralActivity.this, json);
                if (checkCode) {
                    Gson gson = new Gson();
                    IntegralTypeListModel TypeListModel = gson.fromJson(json, IntegralTypeListModel.class);
                    if (TypeListModel.getData().getList().size() > 0) {
                        goods_category_id = TypeListModel.getData().getList().get(0).getGift_category_id();
                        idTvShopType.setText(TypeListModel.getData().getList().get(0).getGift_category_name());
                        idTvShopType.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
                    }
                }
            }

            @Override
            public void onError(Exception e) {
            }
        });
    }

    private void getBM() {
        HttpRequest.postUrl(Api.APP_CREATE_SKU_INTEFRAL)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkcode = Utils.checkCode(mAc, json);
                        if (checkcode) {
                            Gson gson = new Gson();
                            SimpleModel simpleModel = gson.fromJson(json, SimpleModel.class);
                            idEdtCodeNum.setText(simpleModel.getData().getSku());
                        } else {
                            showToast("服务器异常");
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast(e.getMessage());
                    }
                });
    }

    private void initClick() {
        mTextViewtel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBM();
            }
        });

        //商品名称点击时，验证条码唯一性
        idEdtGoodName.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (!isSingleCode) {
                        if (!StringUtils.isEmpty(idEdtCodeNum.getText().toString())) {
                            checkCode();
                        }
                    }
                }
                return false;
            }
        });

        idEdtCodeNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                isSingleCode = false;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }


    //检验是否存在
    private void checkCode() {
        HttpRequest.postUrl(Api.CHECK_CODE_SINGLE)
                .addParams("sku", idEdtCodeNum.getText().toString())
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json, true);
                        if (checkCode) {
                            dialog = new ShopCodeSingleDialog(mAc, "存在相同条码,请重输");
                            dialog.show();
                        } else {
                            isSingleCode = true;
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 101://获取类别
                    String typeID = data.getStringExtra(ShopTypeActivity.SHOP_TYPE_ID);
                    String typeName = data.getStringExtra(ShopTypeActivity.SHOP_TYPE_NAME);
                    if (StringUtils.isEmpty(typeID)) {

                    } else {
                        idTvShopType.setText(typeName);
                        idTvShopType.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_right));
                        goods_category_id = typeID;
                    }

                    break;
                case 102:
                    //处理扫描结果（在界面上显示）
                    if (null != data) {
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        String result = bundle.getString(CaptureActivity.RESULT);
                        idEdtCodeNum.setText(result);
                    }
                    break;
                case 104://图片上传
//                    final ArrayList<BaseMedia> medias = Boxing.getResult(data);
//                    BaseMedia baseMedia = medias.get(0);
//                    if (!(baseMedia instanceof ImageMedia)) {
//                        return;
//                    }
//                    showProgressDialog("请稍等，图片上传中...");
//                    final ImageMedia imageMedia = (ImageMedia) baseMedia;
//                    //对返回的图片进行压缩
//                    if (imageMedia.compress(new ImageCompressor(this))) {
//                        imageMedia.removeExif();
//                    }
//                    //压缩质量和尺寸 上面这个不靠谱
//                    File fileDir = Environment.getExternalStorageDirectory();
//                    BitmapFactory.Options opts = new BitmapFactory.Options();
//                    Bitmap bitmap = BitmapFactory.decodeFile(imageMedia.getPath(), opts);// 文件路径
//                    ImageUtilsK.compressImage2FileBySize(bitmap, new File(fileDir, "ptshop.jpg"));
//                    File file1 = new File(fileDir, "ptshop.jpg");
//                    mPicPath = file1.getAbsolutePath();

//                    mPicPath = imageMedia.getPath();
                    uploadFile(mPicPath);
                    break;
                case PictureConfig.CHOOSE_REQUEST:
                    String uri = PicturePickerHelper.onPickLogoOrAvatarActivityResult(requestCode, resultCode, data);
                    if (!StringUtils.isEmpty(uri)) {
                        uploadFile(uri);
                    } else {
                        showToast("未选择照片");
                    }
                    break;

            }
        }
    }

    //文件上传
    private void uploadFile(final String mPicPath) {
        Map<String, String> paprms = new HashMap<>();
        paprms.put("token", BaseApplication.getToken());
        OkHttpUtils.post()
                .addFile("file", "shop.jpg", new File(mPicPath))
                .url(Api.IMAGE_UPLOAD)
                .params(paprms)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                showToast("上传失败");
                                deleteSingleFile(mPicPath);
                            }
                        });
                    }

                    @Override
                    public void onResponse(final String response, int id) {

                        boolean isChecked = Utils.checkCode(AddIntegralActivity.this, response);
                        if (!isChecked) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissProgressDialog();
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                            GlideUtils.loadImage(AddPtShopActivity.this, new File(mPicPath), idImgAdd1);
//                            Log.d(TAG, "run: " + mPicPath);
                                    idImgDel.setVisibility(View.VISIBLE);
                                    dismissProgressDialog();
                                    ImageUploadModel imageUploadModel = gson.fromJson(response, ImageUploadModel.class);
                                    upload_img_url = imageUploadModel.getData().getPath();
                                    GlideUtils.loadImage(mAc, upload_img_url, idImgAdd1);
                                    PictureFileUtils.deleteCacheDirFile(AddIntegralActivity.this);//清除缓存
                                }
                            });
                        }
                        deleteSingleFile(mPicPath);
                    }
                });

    }

    //上传图片删除
    public void setImages() {
        GlideUtils.loadGlideImage(mAc, R.mipmap.ic_image_add, idImgAdd1);
//        idImgAdd1.setBackgroundResource(R.mipmap.ic_image_add);
        idImgDel.setVisibility(View.GONE);
        upload_img_url = "";
    }

    @OnClick({R.id.id_img_del, R.id.titlebar_iv_left, R.id.titlebar_tv_right, R.id.id_tv_shop_type, R.id.id_img_type, R.id.id_img_code, R.id.id_img_add1, R.id.id_edt_start_time, R.id.id_img_start_time, R.id.id_edt_end_time, R.id.id_img_end_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_img_del://删除图片
                ShopInfoImageDelDialog dialogs = new ShopInfoImageDelDialog(mAc, ShopInfoImageDelDialog.ADDINTERGRALSHOP);
                dialogs.show();

                break;
            case R.id.titlebar_iv_left:
                finish();
                break;
            case R.id.id_tv_shop_type:
            case R.id.id_img_type://分类
                Intent intent = new Intent(this, IntegralTypeActivity.class);
                intent.putExtra(IntegralTypeActivity.SHOP_TYPE_URL, Api.APP_INTEGRAL_TYPE);
                intent.putExtra(IntegralTypeActivity.SHOP_TYPE, IntegralTypeActivity.INTEGRAL);
                startActivityForResult(intent, SHOP_TYPE_CODE);
                break;
            case R.id.id_img_code://条码
                getCameraManifest();
                break;
            case R.id.id_img_add1://添加图片

                PicturePickerHelper.pickLogoOrAvatar(AddIntegralActivity.this);

//                String cachePath = BoxingFileHelper.getCacheDir(this);
//                if (TextUtils.isEmpty(cachePath)) {
//                    Toast.makeText(this, R.string.storage_deny, Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                Uri destUri = new Uri.Builder()
//                        .scheme("file")
//                        .appendPath(cachePath)
//                        .appendPath(String.format(Locale.US, "%s.jpg", System.currentTimeMillis()))
//                        .build();
//                BoxingConfig singleCropImgConfig = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG).withCropOption(new BoxingCropOption(destUri).aspectRatio(1, 1)).needCamera();
//                Boxing.of(singleCropImgConfig).withIntent(this, PhotoPickerActivity.class).start(this, IMG_SELECTION);
                break;
            case R.id.titlebar_tv_right://保存
                httpIsRight();
                break;
            case R.id.id_edt_start_time:
            case R.id.id_img_start_time:
                getTime(idEdtStartTime);
                break;
            case R.id.id_edt_end_time:
            case R.id.id_img_end_time:
                getTime(idEdtEndTime);
                break;
        }
    }

    //参数验证
    private void httpIsRight() {
        if (StringUtils.isEmpty(goods_category_id)) {
            showToast("未选取分类");
            return;
        }
        if (StringUtils.isEmpty(idEdtGoodName.getText().toString())) {
            showToast("未填写名称");
            return;
        }
        if (StringUtils.isEmpty(idEdtCodeNum.getText().toString())) {
            showToast("未填写编码");
            return;
        }

        if (StringUtils.isEmpty(idTvSellPrice.getText().toString())) {
            showToast("未填写所需积分");
            return;
        }
        if (StringUtils.isEmpty(idEdtStock.getText().toString())) {
            showToast("未填写礼品数量");
            return;
        }
        if (StringUtils.isEmpty(idEdtStartTime.getText().toString())) {
            showToast("未填写有效开始时间");
            return;
        }
        if (StringUtils.isEmpty(idEdtEndTime.getText().toString())) {
            showToast("未填写有效结束时间");
            return;
        }
        if (StringUtils.isEmpty(idEdtOrder.getText().toString())) {
            showToast("未填写排序");
            return;
        }
        showProgressDialog("请稍等，数据保存中...");
        saveShopInfo();//保存商品信息
    }


    //保存商品信息
    private void saveShopInfo() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String putTime = formatter.format(curDate);
        PostProcess postProcess = HttpRequest.postUrl(Api.APP_ADD_INTEGRAL)
                .addParams("category_id", goods_category_id + "")//分类id
                .addParams("gift_name", idEdtGoodName.getText().toString())//礼物名称
                .addParams("gift_sku", idEdtCodeNum.getText().toString())//礼物编号
                .addParams("points_price", idTvSellPrice.getText().toString())//兑换积分
                .addParams("gift_stock", idEdtStock.getText().toString())//库存
                .addParams("validity_start", idEdtStartTime.getText().toString())//开始时间
                .addParams("validity_end", idEdtEndTime.getText().toString())//结束时间
                .addParams("gift_image", upload_img_url)//图片
                .addParams("sort", idEdtOrder.getText().toString())//排序
                .addParams("status", mSwitch.isChecked() ? "1" : "0")//是否启用
                .addParams("is_app", mSwitch2.isChecked() ? "1" : "0")//自主兑换
                .addParams("remark", idTvRemarks.getText().toString());//备注
        postProcess.execute(new PostProcess.StringCallBack() {
            @Override
            public void onResponse(final String json) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_LIST_REFRESH, true));
                            CodeMsgBean codeMsgBean = gson.fromJson(json, CodeMsgBean.class);
                            MyToast.showShortToast(mAc, codeMsgBean.getMessage() + "");
                            finish();
                        }

                    }
                });
            }

            @Override
            public void onError(final Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        MyToast.showShortToast(mAc, e.getMessage());
                    }
                });
            }
        });
    }

    //获取照相机权限
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 1;

    private void getCameraManifest() {
        MPermissions.requestPermissions(this, MY_PERMISSIONS_REQUEST_CAMERA, Manifest.permission.CAMERA);
    }

    private void getCamera() {
        Intent intent = new Intent(mAc, CaptureActivity.class);
        startActivityForResult(intent, SHOP_QR_CODE);
    }

    @PermissionGrant(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestSuccess() {
        getCamera();
    }

    @PermissionDenied(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestError() {
        showToast("授权失败！");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }


    //时间
    private int mYear;
    private int mMonth;
    private int mDay;

    private void initDate() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mYear = c.get(Calendar.YEAR);// 获取当前年份
        mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
        mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当前月份的日期号码
    }

    private void getTime(final TextView view) {
        initDate();
        final DatePicker picker = new DatePicker(mAc);
        picker.setCanLoop(false);
        picker.setWheelModeEnable(true);
        picker.setTopPadding(15);
        picker.setRangeStart(1930, 1, 01);
        picker.setRangeEnd(mYear + 100, 11, 11);
        picker.setSelectedItem(mYear, mMonth, mDay);
        picker.setWeightEnable(true);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                view.setText(year + "-" + month + "-" + day);
                view.setTextColor(getResources().getColor(R.color.wjx_content_txt_black_left));
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }


}
